<?php
/**
 * Authenfication Adapter
 *
 * This adapter authenticate if the user is on the DB and return a MSG
 * @version 1.0
 * @package CMS/Auth
 */
class CMS_Auth_Adapter implements Zend_Auth_Adapter_Interface
{
    protected $username;
    protected $password;
    protected $user;
    protected $remember;
    protected $credential;

    /**
     * Constructor
     * @param $user
     * @param $password
     * @param $remember
     * @param credential
     */
    public function __construct($username, $password, $remember = false, $credential = NULL)
    {
        $this->username     = $username;
        $this->password         = $password;
        $this->remember     = $remember;
        $this->credential   = $credential;
    }

    /**
     * Performs an authentication attempt
     * @return Zend_Auth_Result
     * @throws CMS_Auth_Exception
     */
    public function authenticate()
    {
        if ($this->credential != NULL)
        {
            $this->user = User::findOneByCredential($this->credential);
            
            if (!$this->user) {
                return $this->result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID);
            }
            if ($this->user->credential_expires >= time())
            {
                $this->user->credential = NULL;
                $this->user->save();
            }
            else
            {
                return $this->result(Zend_Auth_Result::SUCCESS);
            }
        }
        else
        {
            $this->user = User::findOneByUser($this->username);
        
            if ($this->user)
            {
                if ($this->user->password == md5($this->password))
                {
                    $this->user->credential_expires = time() + 120;

                    $this->user->credential = md5($this->user->username . $this->user->password . $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'] . microtime() );

                    $this->user->save();

                    return $this->result(Zend_Auth_Result::SUCCESS);
                }

                else
                    throw new CMS_Auth_Exception('Wrong password', CMS_Auth_Exception::WRONG_PASS);
            }
            else
                throw new CMS_Auth_Exception('Account not found', CMS_Auth_Exception::ACCOUNT_NOT_FOUND);
        }
        throw new CMS_Auth_Exception('Unknown error', CMS_Auth_Exception::UKNOWN);
    }

    /**
     * Factory for Zend_Auth_Result
     * @param $code The Result code, see Zend_Auth_Result
     * @param $messages The Message, can be a string or array
     * @return Zend_Auth_Result
     */
    public function result($code, $messages = array())
    {
        if (!is_array($messages))
        {
            $messages = array($messages);
        }
        return new Zend_Auth_Result($code, $this->user, $messages);
    }
}

